package com.norther.official.core.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.norther.official.common.util.DateUtils;
import com.norther.official.common.util.MD5UTIL;
import com.norther.official.core.dao.UserRepository;
import com.norther.official.core.dao.specifications.UserSpecifications;
import com.norther.official.core.dto.NorthUserDto;
import com.norther.official.core.entity.NorthUser;
import com.norther.official.core.service.IUserService;

@Service
@Transactional(readOnly=true)
public class UserService implements IUserService {

	@Autowired
	private UserRepository userRepository;

	@Override
	public Page<NorthUser> pageQuery(NorthUserDto dto, Pageable pageable) {

		Specification<NorthUser> specification = UserSpecifications
				.listQueryCriteria(dto);
		Page<NorthUser> page = userRepository.findAll(specification, pageable);
		return page;
	}
	
	@Transactional
	@Override
	public NorthUser saveUser(NorthUser user) {

		Date now = DateUtils.getNowDateTime();
		user.setUpdateTime(now);

		Long id = user.getId();
		String password = user.getPassword();
		if (id == null) {
			user.setCreateTime(now);
		} else {
			NorthUser temp = findUserById(id);
			user.setPassword(temp.getPassword());
		}

		userRepository.save(user);

		// 密码不为空，更新user密码
		if (StringUtils.isNotBlank(password)) {
			changeUserPassword(user.getId(), password);
			user.setPassword(MD5UTIL.encrypt(password));
		} 
		return user;
	}

	@Override
	public NorthUser findUserForLogin(String account, String password) {

		return userRepository.findUserLogin(account, password);
	}

	@Override
	public NorthUser findUserById(Long id) {

		return userRepository.findByIdAndIsDelete(id, 0);
	}
	
	@Transactional
	@Override
	public boolean changeUserPassword(Long id, String password) {
		password = MD5UTIL.encrypt(password);
		return userRepository.updateUserPassword(id, password) == 1;
	}
	
	@Transactional
	@Override
	public int deleteUsers(Long[] ids) {

		return userRepository.deleteByIdIn(ids);
	}

}
